<?php
// 应用公共文件
/**获取当前项目
 * @return mixed|string
 */
function getProject(){
    $project = session('project');
    if(empty($project)){
        $project = cookie('project');
        if(empty($project)){
            $project = app('http')->getName();
        }
    }
    return strtolower($project);
}

/**设置当前项目
 * @param string桑倩项目名称 $str
 * @return bool
 */
function setProject($str=''){
    if(empty($str)){
        $str = request()->controller(true);
    }
    $str = strtolower($str);
    session('project',$str);
    cookie('project',$str);
    return true;
}

/**获取当前所使用的语言
 * @return string
 */
function getLange(){
    $lang = session('lang');
    if(empty($lang)){
        $lang = cookie('lang');
        if(empty($lang)){
            $lang = 'zh';
        }
    }
    return strtolower($lang);
}

/**获取表名称
 * @param string名称 $name
 * @param string应用 $project
 * @param bool是否全名 $whole
 * @return string
 */
function getTable($name='',$project='',$whole=false){
    return $name;
}

/**设置语言
 * @param string语言 $lang
 * @return bool
 */
function setLang($lang='zh'){
    session('lang',strtolower($lang));
    cookie('lang',strtolower($lang));
    return true;
}

/**获取文字翻译内容
 * @param string要翻译的文字 $str
 * @param string要翻译成的语言 $to
 * @param string文字的语言 $from
 * @return bool|mixed|string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function getTranslate($str='',$to='',$from='zh'){
    if(!config('app.fanyi')){
        return $str;
    }
    $from = strtolower($from);
    if(empty($str)){
        return '';
    }
    if(empty($to)){
        $to = getLange();
    }
    $to = strtolower($to);
    if($to==$from){
        return $str;
    }
    if(getTable('lange')!=='admin_lange'){
        $data = \think\facade\Db::name(getTable('lange'))
            ->where($from,$str)
            ->field('id,'.$to)
            ->find();
        if(empty($data)){
            \think\facade\Db::name(getTable('lange'))
                ->insert([
                   $from=>$str
                ]);
            $str = translateStr($str,$to,$from);
        }elseif (empty($data[$to])){
            $str = translateStr($str,$to,$from);
        }else{
            $str = $data[$to];
        }
        return $str;
    }else{
        return false;
    }
}

/**单独翻译数据
 * @param string要翻译的文字 $str
 * @param string要翻译的语言 $to
 * @param string文字的语言 $from
 * @return bool
 */
function translateStr($str = '',$to=null,$from='zh'){
    if(!$to){
        $to = getLange();
    }
    $data = \think\facade\Db::name(getTable('lange'))
        ->where($from,$str)
//        ->whereOr($to,'')
        ->find();
    if(empty($data)){
        \think\facade\Db::name(getTable('lange'))
            ->insert([
                $from=>$str
            ]);
    }
    if($to==$from){
        return $str;
    }
//    $obj = new \app\admin\model\fanyi\FanYi();
    $obj = \app\admin\model\fanyi\FanYi::translate();
    $array = $obj->getFanyi($to,$str);
    if(empty($array)){
        return false;
    }else{
        return $array;
    }

}

/**全面翻译
 * @param string要翻译成的语言 $to
 * @return bool
 */
function translateStrAll($to='zh'){
    if($to=='zh'){
        return true;
    }
    $data = \think\facade\Db::name(getTable('lange'))
        ->where($to,null)
        ->whereOr($to,'')
        ->cursor();
    $str = '';
    $shuju = [];
    $n = false;
    foreach ($data as $key=>$value){
        if(strlen($str)<5500){
            $str .= $value['zh'].'&';
            $shuju[$key] = $value;
        }else{
            $n = true;
            break;
        }
    }
    if(empty($str)){
        return true;
    }
    $obj = \app\admin\model\fanyi\FanYi::translate();
    $array = $obj->getFanyi($to,$str);
    if($array){
        $array = explode('&',$array);
        foreach ($shuju as $value){
            \think\facade\Db::name(getTable('lange'))
                ->where('id',$value['id'])
                ->update([$to=>trim($array[$key])]);
        }
    }
    if($n){
        sleep(60);
        translateStrAll($to);
    }
    return true;
}

/**要获取数据库的配置
 * @param string要获取的配置 $str
 * @param string获取的字段 $field
 * @param null获取的表名称 $table
 * @param null默认 $defult
 * @return array|mixed|null|string|\think\Collection|\think\Db|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function getSysTem($str='',$field='value',$table=null,$defult=null){
    if(empty($str)){
        return '';
    }
    if(!$table){
        $table = getTable('systems');
    }
    $data = [];
    if(is_numeric($str)){
        $data = \think\facade\Db::name($table)
            ->where('id',$str)
            ->find();
    }else{
        $str = explode('.',$str);
        if(is_array($str)){
            if(count($str)==2&&$str[1]){
                $data = \think\facade\Db::name($table);
                if($str[0]??null){
                    $data = $data->where('en_name',$str[0]);
                }
                if($str[1]??null){
                    $data = $data->where('name',$str[1]);
                }
                $data = $data->find();
            }elseif (count($str)==1||!($str[1]??null)){
                $data = \think\facade\Db::name($table)
                    ->where('en_name',$str[0])
                    ->select();
                $newdata = [];
                foreach ($data as $value){
                    if($value['tupian']=='单图片'||$value['tupian']=='单文件'||$value['tupian']=='视频'){
                        $value['value'] = getFilePath($value['value']);
                    }
                    if($value['tupian']=='多图片'||$value['tupian']=='多文件'){
                        $value['value'] = getFilePath($value['value'],true);
                    }
                    if($value['tupian']=='json数组'){
                        $value['value'] = json_decode($value['value'],true);
                    }
                    if($field=='all'){
                        $newdata[$value['name']] = $value;
                    }else{
                        $newdata[$value['name']] = $value[$field];
                    }
                }
                return $newdata;
            }
        }
    }
    if($data??null){
        if($data['tupian']=='单图片'||$data['tupian']=='单文件'||$data['tupian']=='视频'){
            $data['value'] = getFilePath($data['value']);
        }
        if($data['tupian']=='多图片'||$data['tupian']=='多文件'){
            $data['value'] = getFilePath($data['value'],true);
        }
        if($data['tupian']=='json数组'){
            $data['value'] = json_decode($data['value'],true);
        }
        if($field=='all'){
            return $data;
        }else{
            return $data[$field];
        }
    }else{
        if($defult){
            return $defult;
        }else{
            return '';
        }
    }
}

/**获取当前id的文件路径
 * @param string文件id $id
 * @param bool是否返回数组 $isarray
 * @param null是否设置表 $table
 * @param bool是否要带域名 $whole
 * @param string是否有默认值 $defult
 * @return array|mixed|string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function getFilePath($id='',$isarray=false,$table=null,$whole=false,$defult=''){
    $data = \think\facade\Db::name(getTable('enclosure',$table))
        ->where('id','in',$id)
        ->select()->toArray();
//    echo '<pre>';
//    print_r($data);
//    exit;
    if($data){
        $img = [];
        foreach ($data as $value){
            if(!strstr($value['path'],'http')){
                if($whole){
                    $value['path'] = trim(request()->scheme().'://'.request()->host(),'/').$value['path'];
                }else{
                    $value['path'] = $value['path'];
                }
            }else{
                $url = getSysTem(4);
                if(!strstr($value['path'],$url)){
                    $value['path'] = rtrim($url,'/').'/'.$value['new_name'];
                }
            }
            $img[] = $value['path'];
        }
        if($isarray){
            return $img;
        }else{
            return $img[0];
        }
    }else{
        if($isarray){
            if($defult){
                return [$defult];
            }else{
                return ['/static/admin/img/error.jpg'];
            }
        }else{
            if($defult){
                return $defult;
            }else{
                return '/static/admin/img/error.jpg';
            }
        }
    }
}
/**返回json给layui的分页
 * @param $data
 * @return \think\response\Json
 */
function json_page_response($data){
    return json(['code'=>0,'msg'=>getTranslate('获取成功'),'count'=>$data['total'],'data'=>$data['data']]);
}
/**添加后台消息
 * @param $str
 * @return bool
 * @throws \think\Exception
 */
function addAdminMessage($str){
    $data['neirong'] = $str;
    $data['status'] = 0;
    $data['create_time'] = time();
    if(\think\facade\Db::name(getTable('adminmessage'))
        ->insert($data)){
        return true;
    }else{
        return false;
    }
}
/**加密
 * @param $str
 * @param bool $haxi
 * @return bool|string
 */
function pwd_encode($str,$haxi=true){
    $str = trim($str);
    if($haxi){
        return password_hash($str,PASSWORD_DEFAULT);
    }else{
        return md5(md5($str));
    }
}

/**解密
 * @param $str
 * @param $passworder
 * @param bool $haxi
 * @return bool
 */
function pwd_decode($str,$passworder,$haxi=true){
    $str = trim($str);
    if($haxi){
        return password_verify($str,$passworder);
    }else{
        if(md5(md5($str))==$passworder){
            return true;
        }else{
            return false;
        }
    }
}
/**json返回值
 * @param string $msg
 * @param int $code
 * @param null $data
 * @return \think\response\Json
 */
function json_to_respos($msg='成功',$code=200,$data=null){
    return json(['msg'=>getTranslate($msg),'code'=>$code,'data'=>$data]);
}

/**验证
 * @param array $data
 * @param array $array
 * @return mixed
 */
function yanzhen($data=[],$array=[]){
    $validate =\think\facade\Validate::rule($array);
    if(!$validate->check($data)){
        $val['code'] = false;
        $val['msg'] = $validate->getError();
    }else{
        $val['code'] = true;
    }
    return $val;
}

/**将字符串分割成数组
 * @param string元字符串 $str
 * @param string分割符号 $division
 * @return array
 */
function strToArray($str='',$division=''){
    return explode($division,$str);
}

/**将数组链接成字符串
 * @param array数组 $array
 * @param string连接符号 $division
 * @return string
 */
function arrayToStr($array=[],$division=''){
    return implode($division,$array);
}

/**获取七牛云设置
 * @return array|mixed|null|string|\think\Collection|\think\Db|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function isQiNiu(){
//    return false;
    return getSysTem('七牛云设置.是否开启七牛云');
}

/**获取文件所在文件夹
 * @param string $filename
 * @return string
 */
function fileGetDir($filename='/'){
    $filename = rtrim($filename,'/');
    $str = strToArray($filename,'/');
    unset($str[count($str)-1]);
    return arrayToStr($str);
}

/**获取权限
 * @param array $data
 * @return bool
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 */
function getmyauth($data=[]){
    if(empty($data)){
        return false;
    }
    return \app\admin\model\auth\MyAuth::getAuthos($data);
}

/**删除文件夹
 * @param string $dir
 * @return bool
 */
function myrmdir($dir=''){
    if($dir){
        try{
            rmdir($dir);
        }catch (\think\Exception $e){
            chmod($dir,0777);
            rmdir($dir);
        }
    }
    return true;
}

/**添加文件夹爱
 * @param string $dir
 * @return bool
 */
function addDir($dir=''){
    if($dir){
        try{
            $bool = mkdir($dir);
        }catch (\think\Exception $e){
            $newdir = fileGetDir($dir);
            chmod($newdir,0777);
            $bool = mkdir($dir);
        }
        return $bool;
    }
    return true;
}